package com.sgb.knowledgeshare.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.ActivitySharePublishBinding;
import com.sgb.knowledgeshare.entity.TabelListEntity;
import com.sgb.knowledgeshare.utils.PageChangeSharePublicEvent;
import com.sgb.knowledgeshare.utils.RxBus;
import com.sgb.knowledgeshare.view.adapter.LabelAdapter;
import com.sgb.knowledgeshare.viewmodel.SharePublishActivityModel;
import com.sgb.knowledgeshare.weight.MyItemDecoration;
import com.sgb.knowledgeshare.weight.ShareLabelDialog;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.CommonUtils;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.FlowLayoutManager;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.ThreadUtils;
import com.swgk.core.view.entity.VideoTypeListEntity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fq on 2020/9/15 0015
 * Description：分享-发布短视频的界面
 */
public class SharePublishActivity extends AppActivity {
    private static final int COVER_CODE = 102;
    SharePublishActivityModel viewmodel;
    private ActivitySharePublishBinding binding;
    private static final String VIDEO_PATH = "videoPath";
    private static final String TIME_SIZE = "time_size";
    private static final String TYPE = "type";
    private String no;
    private String absolutePath;
    private File file;
    private File currentFile;
    private String typename;
    private List<PickSelectEntity> classDatas;
    private List<List<PickSelectEntity>> typeDatas;
    private String className;
    private String typeName;
    private String type;
    private String type2;
    private String path;
    private int select = 0;
    private LabelAdapter labelAdapter;
    private String labelName;
    private List<String> labelString;

    public static void start(AppActivity context, String videoPath, int timesize, int type, int code) {
        Intent intent = new Intent();
        intent.putExtra(VIDEO_PATH, videoPath);
        intent.putExtra(TIME_SIZE, timesize);
        intent.putExtra(TYPE, type);
        intent.setClass(context, SharePublishActivity.class);
        context.startActivityForResult(intent, code);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
     //   publish = this;
     /*   if (getIntent().getIntExtra(TYPE, 0) == 2) {
            appManager.addActivity(this);
        }*/
        binding = DataBindingUtil.setContentView(this, R.layout.activity_share_publish);
        viewmodel = new ViewModelProvider(this).get(SharePublishActivityModel.class);
        viewmodel.setActivity(SharePublishActivity.this);
        View decor = getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        binding.include.titleView.setText("发布");
        Glide.with(this)
                .asBitmap()
                .load(getIntent().getStringExtra(VIDEO_PATH))
                .apply(new RequestOptions().placeholder(R.drawable.null_img_list))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        saveImageToGallery(getApplicationContext(), resource);
                        binding.sharePublicLogo.setImageBitmap(resource);
                    }
                });
        binding.include.ivBack.setOnClickListener(this);
        binding.sharePublic.setOnClickListener(this);
        binding.shareSaveNative.setSelected(true);
        binding.llShareSaveNative.setOnClickListener(this);
        binding.sharePublicLogo.setOnClickListener(this);
        binding.complete.setOnClickListener(this);
//        视频类型选择点击事件
        binding.sharePublicType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVideoTypeList();
            }
        });
        //评论框的输入监听
        binding.sharePublicText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 50) {
                    CharSequence sequence = s.toString().subSequence(0, 50);
                    binding.sharePublicText.setText(sequence);
                    binding.sharePublicText.setSelection(sequence.length());
                    MToast.showToast(getApplicationContext(), "最长可输入50个文字，请至少输入5个文字！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        labelAdapter = new LabelAdapter(this, new ArrayList<>());
        binding.theLabelGridview.setLayoutManager(new FlowLayoutManager());
     /*   binding.theLabelGridview.addItemDecoration(new MyItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, ScreenUtil.dip2px(20), ScreenUtil.dip2px(20));
            }
        });*/
        binding.theLabelGridview.setAdapter(labelAdapter);
        labelAdapter.setCallback(new LabelAdapter.OnIsDelete() {
            //完成按钮是否显示事件
            @Override
            public void ShowView() {
                binding.complete.setVisibility(View.VISIBLE);
            }
            //标签条目是否选择事件
            @Override
            public void onClick(int position) {
                boolean selected = labelAdapter.getDatas().get(position).isSelected();
                for (TabelListEntity bean:labelAdapter.getDatas()) {
                    bean.setSelected(false);
                }
                labelAdapter.getDatas().get(position).setSelected(!selected);
                labelAdapter.notifyDataSetChanged();
            }
            //添加标签拉起弹窗的操作
            @Override
            public void addLabel() {
                if (labelAdapter.getDatas().get(0).getLabelNo().equals("add")) {
                    ShareLabelDialog.showBottomDialog(viewmodel, labelAdapter.getDatas(),SharePublishActivity.this);
                }
            }

            @Override
            public void delect() {
                ShareLabelDialog.setUserTabList(labelAdapter.getDatas());
            }
        });

    }

    @Override
    protected void init() {
        viewmodel.getLabelByUserNO();
    }

    //   视频类型选择弹窗
    private void showVideoTypeList() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            className = classDatas.get(options1).getProjectscale();
            type = classDatas.get(options1).getNo();
            if (typeDatas.size() == 0 || null == typeDatas.get(options1) || typeDatas.get(options1).size() == 0 || typeDatas.get(options1).get(options2) == null) {
                typeName = "";
                type2 = "";
            } else {
                if (typeDatas.size() > 0) {
                    typeName = typeDatas.get(options1).get(options2).getProjectscale();
                    type2 = typeDatas.get(options1).get(options2).getNo();
                }
            }
            if (!TextUtils.isEmpty(typeName)) {
                select = 1;
                binding.tvType.setText(className + "-" + typeName);
            } else {
                select = 2;
                binding.tvType.setText(className);
            }
        }).build();
        businessOption.setPicker(classDatas, typeDatas);
        businessOption.setSelectOptions(0, 0);
        businessOption.show();
    }


    @Override
    protected void onStart() {
        super.onStart();
        classDatas = new ArrayList<>();
        typeDatas = new ArrayList<>();
//        获取视频类型数据
        viewmodel.getvideoTypeList();

    }

    //    保存视频封面
    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName = "";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        currentFile = new File(appDir, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));

    }

    //上传图片
    private void updataImage(File currentFile) {
        DialogHelper.showProgressDialog(SharePublishActivity.this, null, "视频上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        viewmodel.uploadMutiFileModel(currentFile);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {//返回
            hideKeyboard(getActivity(), binding.sharePublicText);
            finish();
        } else if (id == R.id.share_public) {//发布
            if (CommonUtils.isFastDoubleClick()) {
                return;
            } else {
                sharePublicData();
            }
        } else if (id == R.id.ll_share_save_native) {//是否报存本地
            binding.shareSaveNative.setSelected(!binding.shareSaveNative.isSelected());
            if (binding.shareSaveNative.isSelected()) {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + getIntent().getStringExtra(VIDEO_PATH))));
            }
        } else if (id == R.id.share_public_logo) {//跳转封面选择
               /* Intent intent = new Intent(this,SelectVideoCoverActivity.class);
                intent.putExtra("videoPath",getIntent().getStringExtra(VIDEO_PATH));
                intent.putExtra("time_size",getIntent().getIntExtra(TIME_SIZE,0));
                startActivityForResult(intent,COVER_CODE);*/
        } else if (id == R.id.complete) {
            binding.complete.setVisibility(View.GONE);
            labelAdapter.setAdapterView();
        }
    }

    private void sharePublicData() {
        labelString = new ArrayList<>();
        for (TabelListEntity bean : labelAdapter.getDatas()) {
            if (!bean.getLabelNo().equals("add")) {
                labelString.add(bean.getLabelName());
                if (bean.isSelected()) {
                    labelName = bean.getLabelName();
                }
            }
        }
        String titlename = binding.sharePublicText.getText().toString();
        if (TextUtils.isEmpty(titlename)) {
            MToast.showToast(this, "请输入标题！");
            return;
        }
        if (titlename.length() < 5) {
            MToast.showToast(this, "最长可输入50个文字，请至少输入5个文字！");
            return;
        }
        if (select == 1) {
            //2级都有
            if (classDatas.size() > 0) {
                if (TextUtils.isEmpty(type)) {
                    MToast.showToast(this, "请选择视频类型！");
                    return;
                }
            }
            if (typeDatas.size() > 0) {
                if (TextUtils.isEmpty(type2)) {
                    MToast.showToast(this, "请选择二级分类！");
                    return;
                }
            }
        } else {
            //只有一级
            if (classDatas.size() > 0) {
                if (TextUtils.isEmpty(type)) {
                    MToast.showToast(this, "请选择视频类型！");
                    return;
                }
            }
        }
        binding.sharePublic.setSelected(false);
        updataImage(currentFile);
    }

    private void hideKeyboard(Context activity, EditText sharePublicText) {
        ThreadUtils.runOnSubThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(sharePublicText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }

    private void sharePublic() {
        //获取相应的参数数据
        viewmodel.getVideoParamsSTS(getIntent().getStringExtra(VIDEO_PATH), binding.sharePublicText);
    }

    //    保存视频信息
    public void setAliInfoVideoParamsSTS(String videoId, UploadFileInfo info) {
        viewmodel.getSaveVideo(absolutePath, type, type2, binding.sharePublicText.getText().toString(), videoId, binding.sharePublic,labelName,labelString);
    }

    //    获取到的类型列表
    public void setVideoTypeList(List<VideoTypeListEntity> data) {
        for (VideoTypeListEntity bean : data) {
            if (!bean.getName().equals("全部")) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(bean.getNo());
                entity.setProjectscale(bean.getName());
                if (bean.getName().equals("其他分类")){
                    select = 2;
                    binding.tvType.setText(bean.getName());
                    type = bean.getNo();
                }
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                if (bean.getChildren() != null && bean.getChildren().size() > 0) {
                    for (VideoTypeListEntity.ChildrenBean childrenbean : bean.getChildren()) {
                        if (!childrenbean.getName().equals("全部")) {
                            PickSelectEntity child = new PickSelectEntity();
                            child.setNo(childrenbean.getNo());
                            child.setProjectscale(childrenbean.getName());
                            childList.add(child);
                        }
                    }
                }
                typeDatas.add(childList);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void uploadRefresh(String toString) {
        this.absolutePath = toString;
        sharePublic();
    }

    public void setSucceed() {
        DialogHelper.dismissProgressDialog();
        MToast.showToast(this, "发布成功！");
        if (getIntent().getIntExtra(TYPE, 0) == 2) {
          /*  appManager.finishActivity(ShareRecoedVideoActivity.recoedvideo);
            appManager.finishActivity(ShareVideoCompileActivity.videocompile);
            appManager.finishActivity(SharePublishActivity.publish);*/
            appManager.finishActivity2(ShareRecoedVideoActivity.class);
            appManager.finishActivity2(ShareVideoCompileActivity.class);
            appManager.finishActivity2(SharePublishActivity.class);
            RxBus.getDefault().post(new PageChangeSharePublicEvent(0));
        } else {
            this.setResult(Activity.RESULT_OK);
            finish();
        }

    }

    //返回的标签列表信息
    public void setLabelList(List<TabelListEntity> label) {
        ShareLabelDialog.setLabelList(label);
    }

    //标签弹窗选择的标签数据
    public void setLabelName(TabelListEntity tabellistentity) {
        labelAdapter.getDatas().add(tabellistentity);
        if (labelAdapter.getDatas().size() > 5) {
            labelAdapter.getDatas().remove(0);
        }
        labelAdapter.notifyDataSetChanged();
        //更新用户标签数据信息
        ShareLabelDialog.setUserTabList(labelAdapter.getDatas());
    }

    public void setUserLabelList(List<TabelListEntity> data) {
        int size = labelAdapter.getDatas().size();
        if (size>0){
            labelAdapter.getDatas().clear();
        }
        if (data == null) return;
        labelAdapter.addLabel(data);
        //更新用户标签数据信息
        ShareLabelDialog.setUserTabList(labelAdapter.getDatas());
    }
}
